package game.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSocketClientDemo {

	public static void main(String[] args) {
		send();
	}

	private static void send() {
		System.out.println("发送端发送数据");
		
		try {
			DatagramSocket socket = new DatagramSocket(9004);
			
			byte[] buf = "Hello from sender.".getBytes();
			DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("localhost"), 9001);
			socket.send(packet);
			
			displayReciveInfo(socket);
			
			socket.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private static void displayReciveInfo(DatagramSocket socket) throws IOException {
		byte[] data = new byte[1024];
		DatagramPacket packet = new DatagramPacket(data, data.length);
		socket.receive(packet);
		
		System.out.println("返回的信息：" + new String(data));
		System.out.println("服务端IP: " + packet.getAddress().toString());
		System.out.println("服务端端口：" + packet.getPort());
	}
	
}
